package ru.stepuk.modern.nodes.servers;

import java.util.HashMap;
import java.util.Map;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import ru.stepuk.modern.InvalidModelException;
import ru.stepuk.modern.Model;
import ru.stepuk.modern.Request;
import ru.stepuk.modern.Timeline;
import ru.stepuk.modern.distributions.Distribution;
import ru.stepuk.modern.events.ReleaseServer;
import ru.stepuk.modern.gui.QuantumServerDialog;

/**
 *
 * @author ivan
 */
public class QuantumServer extends Server {

    private boolean lastServed = false;
    private Map<Request, Integer> table = new HashMap<Request, Integer>();
    private double quantum = 1.0;


    {
        icon = new ImageIcon(getClass().getResource("/images/d_quantum.png"));
    }

    public QuantumServer(Model model, Timeline timeline, Distribution distribution) {
        super(model, timeline, distribution);
    }

    public double getQuantum() {
        return quantum;
    }

    public void setQuantum(double quantum) {
        this.quantum = quantum;
    }

    @Override
    public void processRequest(Request request) {
        if (idle) {
            // Normal

            currentRequest = request;

            if (!table.containsKey(currentRequest)) {
                double time = distribution.nextValue();
                int ticks = ((int)Math.floor(time / quantum)) + 1;
                table.put(currentRequest, ticks);
            }

            idle = false;
            timeline.addEvent(timeline.now() + quantum, new ReleaseServer(this));

        } else if ((buffer != null) && (buffer.hasFreeSpace())) {
            buffer.putRequest(currentRequest);
            System.out.println("put in buffer");
        } else {

            System.out.println("Request faiued");
        }
    }

    @Override
    public void validate() throws InvalidModelException {
        super.validate();
        table.clear();
    }

    @Override
    public void releaseRequest() {
        int ticks = table.get(currentRequest);
        ticks--;
        if (ticks == 0) {
            lastServed = true;
            table.remove(currentRequest);
        } else {
            lastServed = false;
        }
        next.processRequest(currentRequest);
    }

    @Override
    public JDialog getPropertiesDialog() {
        return new QuantumServerDialog(this);
    }

}
